#!/bin/sh
LAUNCHER=$(readlink -f "${0}")
HERE="$(dirname "${LAUNCHER}")"
cd "${HERE}/../lib/openra" || exit 1

# APPIMAGE is an environment variable set by the runtime
# defining the absolute path to the .AppImage file
if [ -n "${APPIMAGE}" ]; then
	LAUNCHER=${APPIMAGE}

	# appimaged doesn't update the mime or icon caches when registering AppImages.
	# Run update-desktop-database and gtk-update-icon-cache ourselves if we detect
	# that the desktop file has been installed but the handler is not cached
	if command -v update-desktop-database > /dev/null; then
		APPIMAGEID=$(printf "file://%s" "${APPIMAGE}" | md5sum | cut -d' ' -f1)
		LAUNCHER_NAME="appimagekit_${APPIMAGEID}-openra-{MODID}.desktop"
		LAUNCHER_PATH="${HOME}/.local/share/applications/${LAUNCHER_NAME}"
		MIMECACHE_PATH="${HOME}/.local/share/applications/mimeinfo.cache"
		SCHEME="x-scheme-handler/openra-{MODID}-{TAG}"
		if [ -f "${LAUNCHER_PATH}" ] && ! grep -qs "${SCHEME}=" "${MIMECACHE_PATH}"; then
			update-desktop-database "${HOME}/.local/share/applications"
			if command -v gtk-update-icon-cache > /dev/null; then
				gtk-update-icon-cache ~/.local/share/icons/hicolor/ -t
			fi
		fi
	fi
fi

# Search for server connection
PROTOCOL_PREFIX="openra-{MODID}-{TAG}://"
JOIN_SERVER=""
if [ "${1#${PROTOCOL_PREFIX}}" != "${1}" ]; then
	JOIN_SERVER="Launch.Connect=${1#${PROTOCOL_PREFIX}}"
fi

# Run the game
export SDL_VIDEO_X11_WMCLASS="openra-{MODID}-{TAG}"
./OpenRA Game.Mod={MODID} Engine.LaunchPath="${LAUNCHER}" "${JOIN_SERVER}" "$@"

# Show a crash dialog if something went wrong
if [ $? != 0 ] && [ $? != 1 ]; then
	LOGS="${XDG_CONFIG_HOME:-${HOME}/.config}/openra/Logs"
	if [ ! -d "${LOGS}" ] && [ -d "${HOME}/.openra/Logs" ]; then
		LOGS="${HOME}/.openra/Logs"
	fi

	test -d Support/Logs && LOGS="${PWD}/Support/Logs"
	ERROR_MESSAGE="{MODNAME} has encountered a fatal error.\nPlease refer to the crash logs and FAQ for more information.\n\nLog files are located in ${LOGS}\nThe FAQ is available at http://wiki.openra.net/FAQ"
	if command -v zenity > /dev/null; then
		zenity --no-wrap --error --title "{MODNAME}" --text "${ERROR_MESSAGE}" 2> /dev/null
	elif command -v kdialog > /dev/null; then
		kdialog --title "{MODNAME}" --error "${ERROR_MESSAGE}"
	elif "${HERE}/gtk-dialog.py" test > /dev/null; then
		"${HERE}/gtk-dialog.py" error --title "{MODNAME}" --text "${ERROR_MESSAGE}" 2> /dev/null
	else
		printf "${ERROR_MESSAGE}\n"
	fi
	exit 1
fi
